<template>
  <view class="bg-white">
    <cu-custom bgColor="bg-blue" :isBack="true">
      <block slot="content">详情</block>
    </cu-custom>
    <view class="flex justify-center align-center action margin-top">
      <image
        :src="imageInfo.url"
        mode="aspectFill"
        style="height: 350rpx"
        @click="previewImage(imageInfo.url)"
      />
    </view>
    <view class="flex flex-direction">
      <view class="flex justify-around margin-top padding">
        <view
          class="cu-avatar radius lg margin-right-xs"
          @click="toZone(imageInfo.creator.id)"
          :style="'background-image:url(' + imageInfo.creator.avatar + ');'"
        ></view>
        <view class="content flex flex-direction justify-around">
          <view class="text-cut">{{ imageInfo.creator.nickname }}</view>
          <view class="text-gray text-sm flex margin-right-xs">
            <view class="text-cut">
              <text class="cuIcon-time text-gray margin-right-xs"></text>
              {{ imageInfo.createTime }}
            </view>
          </view>
        </view>
        <view
          class="content flex justify-between align-center"
          style="width: 200rpx"
        >
          <view
            class="margin-right-xs"
            :class="
              userInfo.imageLikeIds &&
              userInfo.imageLikeIds.findIndex((ele) => ele === imageInfo.id) !=
                -1
                ? 'text-blue cuIcon-appreciatefill'
                : 'cuIcon-appreciate'
            "
            @click="handleClickImageLike"
          ></view>
          <view
            class="margin-right-xs"
            :class="
              userInfo.imageCollectionIds &&
              userInfo.imageCollectionIds.findIndex(
                (ele) => ele === imageInfo.id
              ) != -1
                ? 'text-blue cuIcon-favorfill'
                : 'cuIcon-favor'
            "
            @click="handleClickImageCollect"
          ></view>
          <view
            class="cuIcon-share margin-right-xs"
            @click="handleClickShareIcon"
          ></view>
        </view>
      </view>
      <view class="text-black padding" style="padding-bottom: 0"
        >{{ imageInfo.title }}
        <view
          v-show="imageInfo.status === '待审核'"
          class="cu-tag bg-red sm radius"
          style="margin-left: 10px"
          >待审核</view
        >
        <view
          v-show="imageInfo.status === '未通过审核'"
          class="text-red text-sm"
          style="white-space: normal"
        >
          &#9888; 未通过审核，原因：{{ imageInfo.remark }}</view
        >
      </view>
      <view class="text-gray padding" style="padding-top: 5px">{{
        imageInfo.description
      }}</view>
      <view class="label-box">
        <view
          class="cu-tag line-cyan sm radius"
          @click="toLabelImages(item)"
          v-for="(item, index) in imageInfo.label"
          :key="index"
          >{{ item }}
        </view>
      </view>
    </view>
    <view class="cu-form-group margin-top solid-bottom solid-top">
      <textarea
        maxlength="-1"
        placeholder="发表友善的评论"
        v-model="comment"
      ></textarea>
    </view>
    <view
      class="padding flex flex-direction animation-scale-up"
      v-show="comment.length > 0"
      ><button class="cu-btn bg-blue lg" @click="handleSubmitComment">
        发布
      </button></view
    >
    <!-- 下方是评论列表部分 -->
    <view class="content">
      <view
        class="action padding margin-top"
        v-for="(item, index) in commentsPageInfo.records"
        :key="index"
      >
        <view
          class="cu-avatar round lg margin-right-xs comment-avatar fl"
          :style="'background-image: url(' + item.creator.avatar + ');'"
        ></view>
        <view class="action">
          <view class="flex justify-between">
            <view class="text-black">{{ item.creator.nickname }}</view>
            <view class="text-sm text-grey">{{ item.createTime }}</view>
          </view>
          <view class="text-gray text-sm">{{ item.content }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  fetchImageInfoByIdApi,
  addCommentApi,
  fetchCommentsApi,
  cancelImageLikeApi,
  doImageLikeApi,
  cancelImageCollectApi,
  doImageCollectApi,
  fetchUserInfoApi,
} from "../../api/http";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      imageInfo: {
        creator: {},
      },
      comment: "",
      commentsPageInfo: {
        current: 1,
        size: 10,
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo,
      token: (state) => state.token,
    }),
  },
  onLoad: function (option) {
    fetchImageInfoByIdApi(option.id).then((res) => {
      this.imageInfo = res.data;
    });
    if (option.id) {
      this.fetchComments({
        page: this.commentsPageInfo.current,
        limit: this.commentsPageInfo.size,
        topicId: option.id,
      });
    }
  },
  methods: {
    ...mapMutations(["setUserInfo"]),
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        longPressActions: {
          itemList: ["发送给朋友", "保存图片", "收藏"],
          success: function (data) {
            console.log(
              "选中了第" +
                (data.tapIndex + 1) +
                "个按钮,第" +
                (data.index + 1) +
                "张图片"
            );
          },
          fail: function (err) {
            console.log(err.errMsg);
          },
        },
      });
    },
    handleSubmitComment() {
      if (!this.checkIfHasToken()) {
        return;
      }
      if (this.comment === "") {
        uni.showToast({
          icon: "none",
          title: "请先填写评论",
        });
        return;
      }
      addCommentApi({
        createdBy: this.userInfo.id,
        topicId: this.imageInfo.id,
        parentId: 0,
        content: this.comment,
      }).then((res) => {
        uni.showToast({
          title: "评论成功",
        });
        this.fetchComments({
          page: this.commentsPageInfo.current,
          limit: this.commentsPageInfo.size,
          topicId: this.imageInfo.id,
        });
        this.comment = "";
      });
    },
    fetchComments(query) {
      fetchCommentsApi(query).then((res) => {
        this.commentsPageInfo = res.data;
      });
    },
    handleClickImageLike() {
      if (!this.checkIfHasToken()) {
        return;
      }
      const isLike =
        this.userInfo.imageLikeIds.findIndex(
          (ele) => ele === this.imageInfo.id
        ) != -1;
      const data = {
        createdBy: this.userInfo.id,
        imageId: this.imageInfo.id,
        count: 1,
      };
      if (isLike) {
        cancelImageLikeApi(data).then((res) => this.refreshUserInfo());
      } else {
        doImageLikeApi(data).then((res) => this.refreshUserInfo());
      }
    },
    handleClickImageCollect() {
      if (!this.checkIfHasToken()) {
        return;
      }
      const isCollect =
        this.userInfo.imageCollectionIds.findIndex(
          (ele) => ele === this.imageInfo.id
        ) != -1;
      const data = {
        createdBy: this.userInfo.id,
        imageId: this.imageInfo.id,
      };
      if (isCollect) {
        cancelImageCollectApi(data).then((res) => this.refreshUserInfo());
      } else {
        doImageCollectApi(data).then((res) => this.refreshUserInfo());
      }
    },
    refreshUserInfo() {
      fetchUserInfoApi({
        token: this.token,
      }).then((res) => {
        this.setUserInfo(res.data);
      });
    },
    checkIfHasToken() {
      if (!this.token) {
        uni.navigateTo({
          url:
            "../login/login?redirect=" +
            encodeURI("../image_details/image_details?id=" + this.imageInfo.id),
          success: () => {
            uni.showToast({
              title: "登录之后才能进行对象操作",
              icon: "none",
            });
          },
        });
        return false;
      }
      return true;
    },
    toZone(userId) {
      uni.navigateTo({
        url: "../zone/zone?id=" + userId,
      });
    },
    handleClickShareIcon() {
      this.setClipboardData(window.location.href).then((res) => {
        uni.showToast({
          icon: "success",
          title: "链接复制成功",
        });
      });
    },
    setClipboardData(data) {
      return new Promise((success, fail) => {
        // #ifndef H5
        uni.setClipboardData({
          data,
          success,
          fail,
        });
        // #endif

        // #ifdef H5
        const textarea = document.createElement("textarea");
        textarea.value = data;
        textarea.readOnly = true;
        document.body.appendChild(textarea);
        textarea.select();
        textarea.setSelectionRange(0, data.length);
        document.execCommand("copy");
        textarea.remove();
        success(data);
        // #endif
      });
    },
    toLabelImages(labelName) {
      uni.navigateTo({
        url: "../label_images/label_images?name=" + labelName,
      });
    },
  },
};
</script>

<style scoped lang="scss">
.label-box {
  padding: 0 30rpx;
}
</style>
